﻿using System;
using System.Diagnostics;
using System.Xml;
using System.Net.Mail;
using System.Reflection;
using OrbitOne.Elmah.Logic;
using OrbitOne.Elmah.MailNotifier.ArgumentParsing;

namespace OrbitOne.Elmah.MailNotifier
{
    class MailNotifier
    {
        [AutoSetMember("t")]
        static MessageTypes MessageType = MessageTypes.Daily;

        [AutoSetMember("p")]
        static String Parameters = String.Empty;

        enum MessageTypes
        {
            Alert,
            Daily,
        }

        private static Configuration _config;

        static void Main(string[] args)
        {
            _config = Configuration.Load();

            var start = DateTime.Now;

            var smtp = new SmtpClient();

            try
            {
                var xslt = new XmlDocument();
                xslt.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream(
                              "OrbitOne.Elmah.MailNotifier.Resources.email_template.xslt"));

                ParseCommandLine(args);

                if (MessageType == MessageTypes.Daily)
                {
                    DateTime after = DateTime.Now;
                    after = after.DayOfWeek == DayOfWeek.Monday ? after.AddDays(-3) : after.AddDays(-1);
                    after = new DateTime(after.Year, after.Month, after.Day, 8, 0, 0);

                    var bData = ReportingHelper.CreateDailyReportData(_config.ElmahWebSite, after);
                    if (bData != null)
                    {
                        string body = XsltUtil.TransformXml(bData.ToString(), xslt.OuterXml);

                        MailMessage mm = new MailMessage
                                             {
                                                 IsBodyHtml = true,
                                                 Subject =
                                                     string.Format("Elmah daily {0} - {1}",
                                                                   after.ToString("dd/MM/yyyy HH:mm"),
                                                                   DateTime.Now.ToString("dd/MM/yyyy HH:mm")),
                                                 Body = body,
                                                 From = new MailAddress(_config.From),
                                             };

                        foreach (var address in _config.DailyEmails)
                        {
                            mm.To.Add(address);
                        }

                        smtp.Send(mm);
                    }
                }
                else
                {
                    int minutes = int.Parse(Parameters);
                    if (minutes == 0)
                    {
                        minutes = 30;
                    }

                    var bDatas = ReportingHelper.CreateAlertReportsData(_config.ElmahWebSite,
                                                                        minutes,
                                                                        _config.AnonymousErrorCount,
                                                                        _config.AuthenticatedErrorCount);

                    var mm = new MailMessage
                                 {
                                     From = new MailAddress(_config.From),
                                     IsBodyHtml = true
                                 };

                    foreach (var address in _config.AlertEmails)
                    {
                        mm.To.Add(address);
                    }

                    foreach (var kv in bDatas)
                    {
                        string body = XsltUtil.TransformXml(kv.Value.ToString(), xslt.OuterXml);

                        mm.Subject = kv.Key;
                        mm.Body = body;

                        smtp.Send(mm);
                    }
                }
                EventLog.WriteEntry("OrbitOne Elmah MailNotifier",
                                    MessageType + " " + start.TimeOfDay.Add(-DateTime.Now.TimeOfDay));
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine("ex = {0}", ex);
                EventLog.WriteEntry("OrbitOne Elmah MailNotifier", "Processed: " + MessageType + Environment.NewLine +
                                                                   Environment.NewLine + ex, EventLogEntryType.Error, 5000);
            }
        }

        private static void ParseCommandLine(string[] arguments)
        {
            var flags = new FlagCollection();
            var parser = new ArgumentParser(ArgumentFormats.All, false, flags);
            parser.Parse(arguments);
            parser.AutoSetMembers(typeof(MailNotifier));
        }

    }
}
